<?php

namespace Xrfg\Wallet\USDT\Console;

use App\Models\Account;
use App\Models\Coin;
use Illuminate\Console\Command;
use App\Models\Recharge as RechargeModel;
use Xrfg\Wallet\Common\Jobs\RechargeJob;
use Xrfg\Wallet\USDT\Services\USDTWallet;

class Recharge extends Command
{
    public $signature = 'recharge:usdt';

    public $description = 'USDT 充值';

    protected $times = 0;

    protected $coinId;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle(USDTWallet $USDTWallet)
    {
        if (!$this->coinId) {
            $this->coinId = Coin::where('name', 'USDT')->value('id');
        }

        ++$this->times;
        $this->info($this->times);
        $transactions = $USDTWallet->listTransactions(['*', 3000]);
        collect($transactions)
            ->where('confirmations', '>=', 1)
            ->each(function ($transaction) {
                $hash = $transaction['txid'];
                $address = $transaction['referenceaddress'];
                $number = $transaction['amount'];

                // 检查数量
                if ($number) {
                    $isAccountExists = Account::where('coin_id', $this->coinId)
                        ->where('address', $address)
                        ->exists();
                    // 检查地址
                    if ($isAccountExists) {
                        $isRechargeExists = RechargeModel::where('hash', $hash)->exists();
                        // 检查hash
                        if (!$isRechargeExists) {
                            RechargeJob::dispatch($this->coinId, $hash, $number, $address)
                                ->onQueue('recharge');
                        }
                    }
                }
            });

        if ($this->times >= 100) {
            return;
        }
        sleep(10);
        self::handle($USDTWallet);
    }
}
